package com.rcloud.server.sealtalk.service;

import com.rcloud.server.sealtalk.dao.MessageRongCloudSynchronizationMapper;
import com.rcloud.server.sealtalk.domain.GroupMembers;
import com.rcloud.server.sealtalk.domain.MessageRongCloudSynchronization;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 一句话描述功能
 *
 * @author yichat
 * @date create in 17:57 2019/6/17 2019
 */
@Service
public class MessageService extends AbstractBaseService<MessageRongCloudSynchronization, Integer> {
    @Resource
    private MessageRongCloudSynchronizationMapper messageRc;

    @Resource
    private GroupMembersService groupMembersService;

    @Override
    protected Mapper<MessageRongCloudSynchronization> getMapper() {
        return messageRc;
    }

    public List<MessageRongCloudSynchronization> selecLastList(Integer groupId, Integer userId, Long timestamp) {

        Example example = new Example(GroupMembers.class);
        example.createCriteria().andEqualTo("groupId", groupId)
                .andEqualTo("memberId", userId).andEqualTo("isDeleted", GroupMembers.IS_DELETED_NO);

        GroupMembers groupMembers = groupMembersService.getOneByExample(example);

        if (groupMembers == null) throw new AssertionError();

        //进群时间和时间戳做比较
        Long time = groupMembers.getTimestamp();
        if (Objects.nonNull(timestamp)) {
            time = time.compareTo(timestamp) > 0 ? time : timestamp;
        }


        List<MessageRongCloudSynchronization> list = messageRc.selectNewestListByGroup(groupId, time);
        if (Objects.nonNull(list)) {
            Collections.reverse(list);
        }

        return list;
    }
}
